#include "Stack.h"

// 初始化栈 
void StackInit(Stack* ps)
{
	assert(ps);
	ps->capacity = 3;  //?
	ps->top = 0;
	ps->arr = (STDataType*)malloc(sizeof(STDataType)* ps->capacity);
	if (NULL == ps->arr){
		assert(0);     //申请空间失败断言
		return;
	}
}

// 销毁栈 
void StackDestroy(Stack* ps)
{
	assert(ps);
	if (ps->arr){    //栈 不为空
		free(ps->arr);
		ps->arr = NULL;
		ps->capacity = 0;
		ps->top = 0;
	}
}

//检查capacity,扩容
static void CheckCapacity(Stack* ps)
{
	assert(ps);
	if (ps->top == ps->capacity){         //栈满
		int newcapacity = 2 * (ps->capacity);
		//1.开辟新空间
		STDataType* temp = (STDataType*)malloc(sizeof(STDataType) * newcapacity);
		if (NULL == temp){
			assert(0);
			return;
		}
		//2.拷贝元素
		memcpy(temp, ps->arr, sizeof(STDataType)*ps->top);
		//3.释放旧空间,使用新空间
		free(ps->arr);
		ps->arr = temp;
		ps->capacity = newcapacity;
	}
}

// 检测栈是否为空，如果为空返回非零结果，如果不为空返回0 
int StackEmpty(Stack* ps)
{
	assert(ps);
	/*if (ps->arr){
		return 0;
	}
	return -1;*/
	return 0 == ps->top;
}

// 入栈 
void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	CheckCapacity(ps);
	ps->arr[ps->top] = data;
	(ps->top)++;
}

// 出栈 
void StackPop(Stack* ps)
{
	assert(ps);
	if (!StackEmpty(ps)){      //栈不为空
		ps->top--;
	}
}

// 获取栈顶元素 
STDataType StackTop(Stack* ps)
{
	assert(!StackEmpty(ps));     //栈不为空，才有栈顶元素，为空则触发断言
	if (ps->arr){
		return ps->arr[ps->top - 1];
	}
}

// 获取栈中有效元素个数 
int StackSize(Stack* ps)
{
	assert(ps);
	if (ps->arr){
		return ps->top;
	}
	return 0;
}




